import { loadRemoteModule } from '@angular-architects/module-federation';
import { Component } from '@angular/core';
import { Router, Routes } from '@angular/router';
import { routes } from './app-routing.module';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
      private router: Router,
  ) {
  }

  load1() {
    console.log('load1 production', environment.production);
    console.log('load1 router', this.router);
    console.log('load1 routes', routes);
    let newRoutes: Routes = [
      {
        path: 'plugin001',
        loadChildren: () => loadRemoteModule({
          type: 'module',
          exposedModule: './AppModule',
          remoteEntry: environment.production ? '/assets/federation-plugin001/remoteEntry.js' : 'http://localhost:4201/remoteEntry.js',
        }).then(m => m.AppModule),
        // .then(m => this.loadRemoteRootModule(m)),
      },
      ...routes,
    ];
    console.log('load1 newRoutes', newRoutes);
    this.router.resetConfig(newRoutes);
  }

  private loadRemoteRootModule(m: any) {
    console.log('loadRemoteRootModule m', m);
    console.log('loadRemoteRootModule m.AppModule', m.AppModule);
    console.log('loadRemoteRootModule m.AppModule.ɵinj', m.AppModule.ɵinj);
    console.log('loadRemoteRootModule m.AppModule.ɵinj.imports', m.AppModule.ɵinj.imports);
    const appModuleImports = m.AppModule.ɵinj.imports;
    // 直接暴露插件的AppComponent
    const appRoutingModule = appModuleImports.find(
        (i: any) => i.name === 'AppRoutingModule',
    );
    const appRoutingModuleImports = appRoutingModule.ɵinj.imports;
    appRoutingModuleImports[0].providers = [
      appRoutingModuleImports[0].providers.find((s: any) => s?.provide?._desc === 'ROUTES'),
    ];
    appRoutingModuleImports[0].providers[0].useValue = [
      {
        path: '',
        component: m.AppModule.ɵmod.bootstrap[0],
        children: appRoutingModuleImports[0].providers[0].useValue,
      },
    ];
    // 移除插件AppModule中的BrowserModule，防止重复加载报错
    let idx = appModuleImports.findIndex((s: any) => s.name === 'BrowserModule');
    if (idx !== -1) appModuleImports.splice(idx, 1);
    return m.AppModule;
  }

  test() {
    this.router.navigate(['/plugin001/order']);
  }

  test2() {

  }
}
